<template>
  <div class='app-container calendar-list-container'>
    <div class='filter-container'>
      <el-input @keyup.enter.native='handleFilter' style='width: 200px;' class='filter-item' placeholder='商铺名' v-model='listQuery.descr'>
      </el-input>
      <el-input @keyup.enter.native='handleFilter' style='width: 200px;' class='filter-item' placeholder='商铺地址' v-model='listQuery.location'>
      </el-input>
      <el-button class='filter-item' type='primary' v-waves icon='search' @click='handleFilter'>搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="edit">添加</el-button>
      <el-button class="filter-item" type="primary" icon="document" @click="handleDownload">导出</el-button>
      <el-button class='filter-item' type='primary' :disabled="this.sels.length === 0" v-waves icon='delete' @click='handleDel'>删除</el-button>
      <el-checkbox class="filter-item" @change='tableKey=tableKey+1' v-model="showAuditor">显示电话</el-checkbox>
    </div>
    <el-table height="400" @selection-change="selsChange" :key='tableKey' :data='list' v-loading='listLoading' element-loading-text='给我一点时间' border fit highlight-current-row style='width: 100%'>

      <el-table-column type="selection">
      </el-table-column>
      <el-table-column   type="index" width="60">
      </el-table-column>

      <el-table-column  label='名称' prop="descr" width="150">
      </el-table-column>
      <el-table-column label='描述' show-overflow-tooltip width="200" prop="longDescr">
      </el-table-column>
      <el-table-column label='地址' show-overflow-tooltip prop="location">
      </el-table-column>
      <el-table-column v-if='showAuditor' align="center" label="电话" prop="tel">
      </el-table-column>
      <el-table-column label='状态' align="center" width="100">
        <template scope="scope">
          <el-tag size="medium" :type="scope.row.enable === '1' ? 'success' : 'error'">{{scope.row.enable | enableFilter}}</el-tag>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="150">
        <template scope="scope">
          <el-button size="small" type="success" @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button size="mini" type="Success" @click="addFood(scope.row)">添加食品</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show='!listLoading' class='pagination-container'>
      <el-pagination @size-change='handleSizeChange' @current-change='handleCurrentChange' :current-page.sync='listQuery.page'
        :page-sizes='[10,20,30,50]' :page-size='listQuery.limit' layout='total, sizes, prev, pager, next, jumper' :total='total'>
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form class="small-space" :model="temp" :rules="rules" ref="form" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="名称" prop="descr">
          <el-input v-model="temp.descr"></el-input>
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="temp.longDescr"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="temp.location"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="tel">
          <el-input v-model="temp.tel"></el-input>
        </el-form-item>
        <el-form-item v-if="dialogStatus=='update'" label="状态" prop="enable">
          <el-select v-model="temp.enable">
            <el-option label="生效" value="1"></el-option>
            <el-option label="无效" value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="create">确 定</el-button>
        <el-button v-else type="primary" @click="update">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList,create,update,del } from '@/api/rest';
import waves from '@/directive/waves/index.js'; // 水波纹指令

export default {
  name: 'x',
  directives: {
    waves
  },
  data() {
    return {
      sels: [],
      list: null,
      showAuditor: false,
      total: null,
      listLoading: null,
      listQuery: {
        page: 1,
        limit: 20,
        location: undefined,
        descr: undefined,
        sort: '+id'
      },
      temp : {
        id: undefined,
        descr: '',
        longDescr: '',
        location: '',
        tel: '',
        location: '',
        enable: ''
      },
      delids : {
        ids : ''
      },
      textMap: {
        update: '编辑',
        create: '创建'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      tableKey: 0,
      rules: {
        descr: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        tel: [
          { required: true, message: '请输入活动名称', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  filters: {
    enableFilter: function (value) {
      if('1'===value){
        return "有效"
      }
      return "无效"
    }
  },
  methods: {
    getList() {
      console.log(location.href)
      console.log(document.URL)
      this.listLoading = true;
      fetchList(this.listQuery).then(response => {
        // debugger
        this.list = response.data.items;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    addFood(row){
      this.$router.push({ path: 'addFood', query: { restaurant_id: row.id }})
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    selsChange(sels) {  
      this.sels = sels  
    }, 
    handleDel() {
      this.$confirm('删除?', '提示', { type: 'warning' }) 
        .then(async () => { 
          const idg = this.sels.map(item => item.id)
          console.log(idg)
          this.delids.ids = this.sels.map(item => item.id).join()
          const res = await del(this.delids)
          // debugger
          if(res.data.code==1){
            for (const y of idg) {
              for (const v of this.list) {
                if (v.id === y) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1)
                  break
                }
              }
            }
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          }else{
            this.$notify({
              title: '失败',
              message: '删除失败',
              type: 'error',
              duration: 2000
            })
          }
        }
        ).catch(() => {
          this.$notify({
            title: '失败',
            message: '删除失败',
            type: 'error',
            duration: 2000
          })
        })
    },
    create() {
      // validate
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          const res = await create(this.temp)
          // debugger
          if(res.data.code==1){
            this.temp.id=res.data.item.id
            this.temp.enable='1'
            this.list.unshift(this.temp)
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          }else{
            this.$notify({
              title: '失败',
              message: '创建失败',
              type: 'error',
              duration: 2000
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
        this.dialogFormVisible = false
      })
    },
    update() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          console.log(Date.parse(new Date()))
          setTimeout(function() {
            console.log(Date.parse(new Date()))
          }, 5000);
          const res = await update(this.temp)
          console.log(res)
          if(res.data.code==1){
            for (const v of this.list) {              
              // console.log(this.list)
              // console.log(v)
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            
          console.log(Date.parse(new Date()))
          }else{
            this.$notify({
              title: '失败',
              message: '更新失败',
              type: 'error',
              duration: 2000
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
        this.dialogFormVisible = false
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        descr: ''
      }
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleDownload() {
      require.ensure([], () => {
        const { export_json_to_excel } = require('vendor/Export2Excel')
        const tHeader = ['ID', '名称', '描述', '地址', '电话']
        const filterVal = ['id', 'descr', 'longDescr', 'location', 'tel']
        const data = this.formatJson(filterVal, this.list)
        export_json_to_excel(tHeader, data, 'table数据')
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'tel') {
          return '不可下载'
        } else {
          return v[j]
        }
      }))
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    }
  }
};
</script>